#!/usr/bin/env python
# -*- coding:utf-8 -*-
# 分析附件中的邮件日志maillog，把id、状态、IP地址和目标邮箱提取出来。并统计出现错误最多的是那种邮箱。
import re

# 统计失败的邮件类型和次数
def count_failed(records_list):
    pattern_mail = r'([\w\.-]+)@([\w\.-]+)'
    failed_list = {}
    for item in records_list:
        if item.get('status') and item['status'] != "success":
            result = re.findall(pattern_mail, item['email'])
            email = result[0][1]
            if failed_list.get(email):
                failed_list[email] = failed_list[email] + 1
            else:
                failed_list[email] = 1
    return failed_list

#找出失败最多的邮件类型
def find_max_failed_email(failed_list):
    max_failed_emails = []
    max_count = 0
    for item in failed_list:
        if failed_list[item] >= max_count:
            max_count = failed_list[item]
            record = {}
            record[item] = max_count
            max_failed_emails.append(record)
    return max_failed_emails


# 统计日志中的id，email，staus, ip地址
def read_line(filename):
    pattern1 = r'(^@.{24} starting delivery \d{4}: msg \d{6} to remote [\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+)'
    pattern2 = r'(^@.{24} delivery \d{4}: [A-Za-z]+: ((2(5[0-5]|[0-4]\d))|[0-1]?\d{1,2})(\.((2(5[0-5]|[0-4]\d))|[0-1]?\d{1,2})){3})'
    records = []
    with open(filename, 'r') as f:
        num = 0
        for line in f.readlines():
            result = re.findall(pattern1, line)
            result2 = re.findall(pattern2, line)
            if result:
                record = {}
                id = re.sub(r':', "", result[0][0].split()[3])
                email = result[0][0].split()[8]
                record['id'] = id
                record['email'] = email
                records.append(record)

            if result2:
                id2 = re.sub(r':', "", result2[0][0].split()[2])
                status = re.sub(r':', "", result2[0][0].split()[3])
                ip_addr = result2[0][0].split()[4]
                for item in records:
                    if item['id'] == id2:
                        item['status'] = status
                        item['ip_addr'] = ip_addr
    return records


if __name__ == "__main__":
    file = './maillog.txt'
    records = read_line(file) # 统计ID，Email，status 和 IP

    failed_records = count_failed(records) # 统计失败的status的次数

    max_failed_emails = find_max_failed_email(failed_records) # 找出失败次数最多的

    print("All records: {}".format(records))
    print("The mail type which failed max times: {}".format(max_failed_emails))